<!--
*@Author: QWP
*@Description: 设置节点的处理人
*@Date: 2024-08-14 13:43:14
-->
<template>
  <a-layout class="s-bg-white">
    <u-form :model="form"
      :elements="fromEls">
      <template #reamrk>
        <span style="color: darkorange">1、设置或修改处理人规则后，需要保存发布才可生效</span> <br/>
        <span style="color: darkorange">2、设置已处理人页签中未选择角色人员信息，且多人处理页签中未选择集合，则由上一步审核人员自行选择审核人员</span>
      </template>
    </u-form>
    <template>
      <u-edit-table :data="userDatas"
        :columns="userCols">
      </u-edit-table>
    </template>
  </a-layout>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, onUnmounted, h, nextTick, watch, toRaw } from 'vue' 
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { Button } from 'ant-design-vue'
import { getOrgData } from '@bs/orgm/orgm';
import { useTaskRuleStore, useLoginStore } from '@/store'
import { evectionUserTree } from '@/service/administration/travel'
import * as userApi from '@/service/system/user'
import { messageC, nullC, isValue } from '@/util/common'
import { useDisTreeParent } from '@/hooks/useTree'
import { bpmnEventBus } from '@/util/eventBus'
import {
  setAssigneeUserWithTaskId,
  getAssigneeUserWithTaskId,
  deleteAssigneeUser,
  setFlowAttrs
} from '@bs/process/process';

const props = defineProps<{
  id: string,
  type: string,
  element: any,
}>()

const { taskRules, startRules } = storeToRefs(useTaskRuleStore())
const { userInfo } = storeToRefs(useLoginStore())

onMounted(() => {
  bpmnEventBus.on('clearDealUser', (value, xmlEl) => {
    if(value == 'Null') {
      form.byParams = '';
    } else {
      form.userlist = [];
      form.role = ''
      form.customParam = '',
      form.byParams = 'usr';
    }
    updateElementTask('taskRules', true, xmlEl)
    saveAssigneeByUser('byParams', xmlEl)
  })
})

const baseData = reactive({
  rules: [ // taskRules
    { taskRuleName: '按指定的人员', ruleKey: "byUser" },
    { taskRuleName: '按指定的角色', ruleKey: 'byRole' },
    { taskRuleName: '按开发者指定参数', ruleKey: 'byParams' },
  ],
  roles: [],
  users: [],
})
const form = reactive({
  taskRules: ''
})
const formItemProps = { labelWidth: '100px', wrapCol: 24 }
const fromEls = reactive([
  { label: '处理人规则', key: 'taskRules', element: 'select', formItemProps,
    col: { span: computed(() => taskType.value == 'bpmn:StartEvent' ? 24 : 0) }, 
    componentProps: { 
      options: computed(() => baseData.rules),
      fieldNames: { label: 'taskRuleName', value: 'ruleKey' },
      onChange: function() {
        form.role = ''
        form.customParam = '',
        updateElementTask('taskRules',)
        form.byParams = ''
        saveAssigneeByUser('byParams')
      }
    }
  },
  // { label: '角色人员信息', key: 'userlist', element: 'treeselect', formItemProps, 
  { label: '角色人员信息', key: 'userlist', element: 'selRoleUserTree', formItemProps, 
    col: { span: computed(() => taskType.value == 'bpmn:StartEvent' ? 0 : 24) }, 
    componentProps: { 
      fieldNames: { label: 'name', value: 'keyid' },
      extraData: computed(() => baseData.roles),
      disabled: true,
      multiple: true,
      isLoadData: false,
      checkStrictly: true,
      class: 'f-normal-disable',
      parent: { key: 'roleName', valueKey: 'fkparentid', parentTLable: '角色名称' },
      onChange: (keys, options) =>  {
        saveAssigneeByUser('byUser')
        if((keys || []).length != 0) {
          form.byParams = ''
          saveAssigneeByUser('byParams')
          bpmnEventBus.emit('clearMoreUser', props.element)
        }
      }
    }
  },
  { label: '角色信息', key: 'assigneeRoles', element: 'select', formItemProps, 
    col: { span: computed(() => form.taskRules == 'byRole' ? 24 : 0) }, 
    componentProps: { 
      options: baseData.roles,
      onChange: () =>  {
        saveAssigneeByUser('byRole')
      }
    }
  },
  { label: '自定义参数', key: 'byParams', element: 'input', formItemProps,
    col: { span: computed(() => taskType.value == 'bpmn:StartEvent' ? 0 : 24) }, 
    componentProps: { 
      disabled: true,
      onChange: () =>  {
        saveAssigneeByUser('byParams')
      }
    }
  },
  { label: '设置说明', col: { span: 24 }, key: 'reamrk', element: 'slot', formItemProps}
])

const userDatas = ref<any[]>();
const userCols = [
  { title: '姓名', key: 'name', width: 100, element: 'select', },
  { title: '账号', key: 'account', width: 100, },
  { title: '部门', key: 'deptname', width: 100, },
  { title: '操作', key: 'do', width: 100, align: 'center',
    customRender: ({ record }) => {
      return h(Button, { type: 'link' }, "删除")
    }
  },
]

const taskType = ref<string>('')
const taskList = ref<any[]>([])

watch(() => props.id, (nval, oval) => {
  nextTick(() => {
    resetTaskForm()
  })
}, { immediate: true })

async function taskLoad() {
  taskType.value = '';
  const element = toRaw(props.element)
  if (props.element.businessObject.$type == 'bpmn:StartEvent') {
    taskType.value = 'bpmn:StartEvent';
  } else {
    const taskInComing = element.businessObject.incoming;
    if(taskInComing) {
      const taskSourceRef = taskInComing[0].sourceRef;
      taskType.value = taskSourceRef.$type;
    }
    // taskType = props.element.businessObject.$type;
  }
  if (taskType.value == 'bpmn:StartEvent') {
    baseData.rules = startRules.value;
    form.taskRules = 'byStarter'
    updateElementTask('taskRules')
  }
  let tasks = element.children;
  if(element.type == "bpmn:UserTask") {
    tasks = element.parent.children;
  }

  let assignee = element.businessObject.assignee || ''
  let candidateUsers = element.businessObject.candidateUsers || ''
  if(assignee) {
    form.byParams = assignee.replace(/\$*{*}*/g, '')
  } else {
    let candidateUsers = element.businessObject.candidateUsers || ''
    candidateUsers = candidateUsers.indexOf('$') != -1 ? '' : candidateUsers
    // form.userlist = candidateUsers.indexOf('byStarter') != -1 ? 'byStarter' : candidateUsers.split(',').filter(item => isValue(item))
    form.userlist = candidateUsers.split(',').filter(item => isValue(item))
  }
}

function resetTaskForm() {
  getRoles()
  taskLoad();
}

//规则选择
function updateElementTask(key, isMoreDeal: boolean = false, xmlEl?: any) {
  const taskAttr = Object.create(null);
  const tElement = xmlEl ? xmlEl : props.element
  if(isMoreDeal == true && !(tElement.id || '').includes('byStarter')) {
    taskAttr['candidateUsers'] = '';
  }
  else if (key == 'taskRules') {
    if(form[key] == 'byStarter') {
      taskAttr['candidateUsers'] = '${' + tElement.id + '}';
    } else {
      let keyVal = form[key] ? '_' + form[key] : ''
      taskAttr['candidateUsers'] = '${' + tElement.id + keyVal + '}';
    }
  }
  try {
    window.bpmnInstances.modeling.updateProperties(toRaw(tElement), taskAttr);
  } catch (error) {}
}

// 获取角色人员信息数据
function getRoles() {
  if(baseData.roles.length != 0) {
    return
  }
  userApi.roleuserselectdata().then(res => {
    if(res.code == 0) {
      baseData.roles = res.data || [];
    }
  })
}

//根据指定用户规则，设置任务处理人
function saveAssigneeByUser(key, xmlEl?: any) {
  const tXmlEl = xmlEl ? xmlEl : props.element
  let task_def_key = tXmlEl.id + "_" + key;
  let selectData = null;
  const taskAttr = Object.create(null);
  if (key == 'byUser') {
    selectData = form.userlist;
    taskAttr['candidateUsers'] = `${selectData.join()}`;
  } 
  else if (key == 'byRole') {
    if((form.roles || []).length == 0) {
      messageC('请选择角色', "warning");
      return;
    }
    selectData = (form.assigneeRoles || []).map(item => {
      return { id: element, name: ''  }
    });
  } 
  else if (key == 'byParams') {
    if((tXmlEl.id || '').includes('byStarter')) {
      taskAttr['assignee'] = ''
    }
    else {
      taskAttr['assignee'] = !isValue(form.byParams) ? '' : '${' + form.byParams + '}';
    }
  }
  
  window.bpmnInstances.modeling.updateProperties(toRaw(props.element), taskAttr);
  try {
  } catch (error) {}
}

onUnmounted(() => {
  bpmnEventBus.off('clearDealUser')
  bpmnEventBus.off('clearMoreUser')
})

</script>

<style lang='scss' scoped>
</style>